<template>
  <div class="AlarmTypeDialog" v-if="reload">
    <!-- <div v-show="loading" class="realTime-ala-loading" ref="realTimealaloading"></div> -->
    <div class="dialog-top">
      <div class="dialog-top-group">
        <div class="dialog-top-item" v-for="(item, index) in alarmInfo.aiAlarmCountForGrade" :key="index"
          :class="item.grade">
          <div class="title">
            {{ item.title }}
          </div>
          <div class="number">
            <CountUp :end-val="item.number"></CountUp>
          </div>
        </div>
      </div>
    </div>
    <div class="dialog-center">
      <!-- <div class="empty-text" v-if="empty">
        <el-empty :image-size="100" description="暂无数据" />
      </div> -->
      <div class="tree">
        <div class="tree-item" v-for="(item, index) in alarmInfo.data" :key="index">
          <div class="tree-item-level0" @click.stop="renderChildren(item, index)">
            <div class="img">
              <img :class="activeIndex == index ? 'rotate' : ''" :src="requireImgUrl('image', '更多')" alt="" />
            </div>
            <div class="title">
              {{ item.equipmentName }}
            </div>
          </div>
          <div class="tree-item-leave1" :style="{
    height: activeIndex == index ? 'fit-content' : 0,
  }">
            <div class="children-item" v-for="(c, i) in item.resetList" :key="i">
              <div :class="c.alertGrade">
                {{ renderStatus(c.alertGrade) }}
              </div>
              <div class="alertContent" :title="c.alertContent">
                {{ c.alertContent }}
              </div>
              <div class="alertTime" :title="c.alertTime">
                {{ renderDate(c.alertTime) }}
              </div>
              <div class="btn">
                <el-button v-if="c.handleStatus == '0'" type="primary" @click="instance(item.id, c)"
                  @click.stop>处理</el-button>
              </div>
            </div>

          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="tsx">
import { ref, toRefs, watch, onMounted, nextTick, onUnmounted ,shallowRef} from 'vue';
import lottie from 'lottie-web';
import jsonData from './loading5-color-data.json';
import { requireImgUrl } from '@/utils/localurl/metaUrl';
import { useIds } from '@/stores/screen/ids';
import { NewGeneral } from '@/api/screen/equipment';
import { useAlertDetailStore } from '@/stores/alertDeail';
import { getAlertMessageDetail, getAlertMessageDetails } from "@/api/alert";
import emits from '@/utils/emits';
import { ElMessage } from 'element-plus';
import type { PropType } from "vue";
// import { addDialog, closeDialog, closeAllDialog, updateDialog } from '@/components/redialog';
import '@/components/redialog/style/alertDialog.scss';
import pLimit from 'p-limit';
import { renderStatus, renderDate } from '@/utils/tool';
import { getEqDetails } from '@/api/equipment';
import { handleAlertMessage } from '@/api/alert';
import { addDialog } from "@/components/custom-dialog/index";
import CustomAlertDialog from '@/components/custom-alert-dialog/index.vue';
const alertDetailStore = useAlertDetailStore();
const { getsessionStorage } = useIds();
interface Data {
  name: string,
  code: string,
  icon: string,
  color: string,
  undo: number,
  total: number,
  key: string,
  parentsKey: string
};
const props = defineProps({
  alarmInfo: {
    type: Object as PropType<any>,
    default: {}
  }
});
const loading = ref(true);
const empty = ref(false);
const childrenList = ref([]);
const activeIndex = ref(-1);
const resetList = ref([]);
const el_loading = ref(true);
const { alarmInfo } = toRefs(props);
const alarmList_id = ref();
// AI告警等级统计（不同等级）  ---- 第一条为未处理非INFO
let aiAlarmCountForGrade = ref([
  {
    code: "AI_ALERT_TODAY_FOR_STATUS",
    key: "AI_ALERT_TODAY_FOR_STATUS_INFO",
    grade: "INFO",
    title: '未处理',
    number: 0
  },
  {
    code: "AI_ALERT_UNDEAL_TODAY_FOR_GRADE",
    key: "AI_ALERT_UNDEAL_TODAY_FOR_GRADE_WARN",
    grade: "WARN",
    title: '告警',
    number: 0
  },
  {
    code: "AI_ALERT_UNDEAL_TODAY_FOR_GRADE",
    key: "AI_ALERT_UNDEAL_TODAY_FOR_GRADE_ERROR",
    grade: "ERROR",
    title: '紧急',
    number: 0
  }
]);
let AiAlarmList = ref([]);
const getAiAlarmCountForGradeList = async () => {
  let config = [];
  aiAlarmCountForGrade.value.forEach(item => {
    // 对象有这个ID则添加一条属性没有则不添加
    if (item.code == "AI_ALERT_TODAY_FOR_STATUS") {
      config.push({
        code: item.code,
        key: item.key,
        params: {
          equipmentIds: getsessionStorage(),
          handleStatus: 0
        }
      });
    }
    else {
      config.push({
        code: item.code,
        key: item.key,
        params: {
          equipmentIds: getsessionStorage(),
          alertGrade: item.grade,
          algCode: alarmInfo.value.code
        }
      });
    };
  });
  // 数组对象去重
  config = config.filter((item, index, self) => {
    return index === self.findIndex((t) => {
      return t.key === item.key;
    });
  });
  if (config.length > 0) {
    let total = 0
    let res = await NewGeneral(config) as any;
    if (res.code === 200) {
      // 判断对象是否为空
      if (Object.keys(res.data).length === 0) {
        return;
      };
      aiAlarmCountForGrade.value.forEach(item => {
        for (let key in res.data) {
          console.log(res.data, 'res.data');

          if (key === item.key && key != "AI_ALERT_TODAY_FOR_STATUS_INFO") {
            item.number = res.data[key].data;
            total += res.data[key].data;
          };
        };
      });
      let index = aiAlarmCountForGrade.value.findIndex(item => item.code === "AI_ALERT_TODAY_FOR_STATUS")
      if (index !== -1) {
        aiAlarmCountForGrade.value[index].number = total;
      };
    };
  };
};
let reload = ref(true)
// 获取AI告警消息列表
const getAiAlarmList = async () => {
  let config = [
    {
      code: "AI_ALERT_MSG_LIST_TODAY_UNDEAL",
      params: {
        equipmentIds: getsessionStorage(),
        algCode: alarmInfo.value.code
      }
    }
  ];
  let res = await NewGeneral(config) as any;
  if (res.code == 200) {
    if (Object.keys(res.data).length === 0) {
      return;
    };
    if (res.data["AI_ALERT_MSG_LIST_TODAY_UNDEAL"].data.length > 0) {
      AiAlarmList.value = res.data["AI_ALERT_MSG_LIST_TODAY_UNDEAL"].data;
    };
  };
};
const instance = (messageId, item: any) => {
  console.log(item);
  
  addDialog({
            title: "告警详细信息",
            width: "600px",
            draggable: false,
            modal: true,
            closeOnClickModal: true,
            Zindex: 9999,
            props: {
                data: {
                    info: {
                        告警内容: item.alertContent,
                        告警等级: item.alertGrade,
                        告警时间: item.alertTime,
                        设备名称: "有害气体检测仪",
                        设备位置: "一区东北角",
                        气体浓度: '32PPM',
                        告警ID: item.alertID,
                        告警父级: item.parentsKey,
                 
                    },
                    imgSrc: requireImgUrl("image", "气体报警"),
                    showSomeDetail: true,
                    bottomBtn: true,
                    WorkerOrder: false,
                },
            },
            component: shallowRef(CustomAlertDialog),
            callBack: (data: any) => {
                //当弹窗任务结束后，调用父页面的回掉函数。（比如我新增完成了需要刷新列表页面）
                console.log("回调函数", data);
            },
        });
















  // const testclose = (options, index) => {
  //   return () => closeDialog(options, index);
  // };



  // let alertMessage = {
  //         equipmentId: 123,
  //         alertMessageId: 123,
  //         alertContent: 124,
  //         alertGrade: 124141,
  //         handleStatus: 0,
  //         imgFlag: 12412,
  //         equipmentName: 124124,
  //         equipmentType: 26236,
  //         equipmentLocation: 1535,
  //         imageUrl: '气体报警',
  //         timeOfDuration: 435435,
  //         equipmentLocationCode: 346346,
  //         alertToneUrl: null,
  //         latestAlertTime: 346346,
  //         alertType: 'detail',
  //         id: 7876
  //       };

  //       alertDetailStore.SetMessage(alertMessage);
  //       addDialog({
  //         contentRenderer: ({ options, index }) => (
  //           <alertDialog closeFn={testclose(options, index)}> </alertDialog>
  //         ),
  //         class: "alertDialog",
  //         headerRenderer: ({ close, titleId, titleClass }) => (
  //           // jsx 语法
  //           <reHeader
  //             headerId={titleId}
  //             headerClass={titleClass}
  //             closeFn={close}
  //             headerTitle={"处理告警"}
  //           >
  //             {" "}
  //           </reHeader>
  //         ),
  //         hideFooter: true,
  //       });
  // getAlertMessageDetail(messageId).then((res) => {
  //   if (res.data.handleStatus == '0') {
  //     getEqDetails(res.data.businessId).then((res1) => {
  //       let alertMessage = {
  //         equipmentId: res1.data.businessId,
  //         alertMessageId: item.messageId,
  //         alertContent: item.alertContent,
  //         alertGrade: item.alertGrade,
  //         handleStatus: item.handleStatus,
  //         imgFlag: res.data.imgFlag,
  //         equipmentName: res.data.equipmentName,
  //         equipmentType: res.data.equipmentType,
  //         equipmentLocation: res1.data.equipmentLocation,
  //         imageUrl: item.imageUrl,
  //         timeOfDuration: item.timeOfDuration,
  //         equipmentLocationCode: res1.data.equipmentLocationCode
  //           ? res1.data.equipmentLocationCode
  //           : "",
  //         alertToneUrl: null,
  //         latestAlertTime: res.data.latestAlertTime,
  //         alertType: 'detail',
  //         id: item.id
  //       };

  //       alertDetailStore.SetMessage(alertMessage);
  //       addDialog({
  //         contentRenderer: ({ options, index }) => (
  //           <alertDialog closeFn={testclose(options, index)}> </alertDialog>
  //         ),
  //         class: "alertDialog",
  //         headerRenderer: ({ close, titleId, titleClass }) => (
  //           // jsx 语法
  //           <reHeader
  //             headerId={titleId}
  //             headerClass={titleClass}
  //             closeFn={close}
  //             headerTitle={"处理告警"}
  //           >
  //             {" "}
  //           </reHeader>
  //         ),
  //         hideFooter: true,
  //       });
  //     });
  //   } else {
  //     ElMessage.warning('该告警已被处理过！')
  //   }

  // });


}
const renderChildren = (item, index) => {
  if (activeIndex.value == index) {
    activeIndex.value = -1;
    return;
  }
  else {
    activeIndex.value = index;
    alarmList_id.value = item.id;
    if (alarmList_id.value) {
      getList(alarmList_id.value);
    };
  };
};
const getList = async (messageId) => {
  el_loading.value = true
  var d = new Date();
  d.setTime(d.getTime() - 1 * 24 * 60 * 60 * 1000);
  var yday = new Date();
  var date =
    d.getFullYear() +
    "-" +
    (d.getMonth() + 1).toString().padStart(2, "0") +
    "-" +
    d
      .getDate()
      .toString()
      .padStart(2, "0");
  yday.setTime(yday.getTime() + 24 * 60 * 60 * 1000);
  var ydate =
    yday.getFullYear() +
    "-" +
    (yday.getMonth() + 1).toString().padStart(2, "0") +
    "-" +
    yday
      .getDate()
      .toString()
      .padStart(2, "0");
  childrenList.value = [];
  let queryForm = {
    handleStatus: "0",
    startTime: date,
    endTime: ydate,
    messageId: String(messageId),
    order: "",
    orderType: "",
    pageNum: 1,
    pageSize: 10000
  };
  let res = await getAlertMessageDetails(queryForm) as any;
  if (res.code == 200) {
    el_loading.value = false;
    let list: [] = res.data.records
    let d = new Date().getTime()
    // childrenList.value = res.data.records;
    list.forEach((item: any) => {
      item.timeOfDuration = (d - new Date(item.alertTime).getTime()) / 1000
    })
    childrenList.value = list
    console.log(childrenList.value);

  };
};
const initData = () => {
  //并发
  const limit = pLimit(1);
  //获取 首页3个统计数据
  const input = [limit(() => getAiAlarmCountForGradeList()), limit(() => getAiAlarmList())];
  Promise.all(input);
};
const reData = () => {
  console.log(activeIndex.value, '999999');

  if (activeIndex.value != -1) {
    getList(alarmList_id.value)
  }
}
onMounted(() => {
  nextTick(() => {
    // initData();
    // emits.on("HANDLE_MESSAGE", initData);
    // emits.on('Handle_Detail',initData)
    // emits.on('Handle_Detail',reData)
  });

});
onUnmounted(() => {
  //  emits.off("HANDLE_MESSAGE", initData);
  //  emits.off('Handle_Detail', reData)
  //  emits.off('Handle_Detail', initData)
});
// watch(() => aiAlarmCountForGrade.value, (newVal) => {
//   if (newVal && newVal.length > 0) {
//     aiAlarmCountForGrade.value = newVal;
//     loading.value = false;
//     console.log('事件告警等级数组======================>', aiAlarmCountForGrade.value);
//   }
// },
//   {
//     immediate: true,
//     deep: true
//   });
// watch(() => AiAlarmList.value, (newVal) => {
//   if (newVal && newVal.length > 0) {
//     AiAlarmList.value = newVal;
//     empty.value = false;
//   }
//   else {
//     empty.value = true;
//   }
//   console.log('事件消息列表==========================>', newVal);
// },
//   {
//     immediate: true,
//     deep: true
//   });
// watch(() => childrenList.value, (newVal) => {
//   if (newVal) {
//     resetList.value = newVal;
//   };
// },
//   {
//     immediate: true,
//     deep: true
//   });
</script>
<style lang="scss" scoped>
.AlarmTypeDialog {
  width: 100%;
  height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  // 溢出
  overflow-y: auto;
  scrollbar-width: none;
  cursor: pointer;
  -ms-overflow-style: none;

  &::-webkit-scrollbar {
    display: none;
    /* Chrome Safari */
  }

  .dialog-top {
    width: 100%;
    height: 15%;

    .dialog-top-group {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .dialog-top-item {
        width: 33%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        .title {
          color: rgba(191, 191, 191, 1);
          font-size: clamp(1.125rem, 0.94vw, 2.25rem);
        }

        .number {
          font-size: clamp(1.5rem, 1.25vw, 3rem);
          color: rgba(38, 190, 255, 1);
          font-family: DigitalNumbers;
          font-weight: 400;
        }

        &.WARN {
          .number {
            color: rgba(255, 207, 38, 1);
          }
        }

        &.ERROR {
          .number {
            color: rgba(224, 73, 40, 1);
          }
        }
      }
    }
  }

  .dialog-center {
    width: 100%;
    height: 85%;

    .tree {
      width: 100%;
      height: 100%;

      .tree-item {
        width: 100%;
        position: relative;
        transition: all 0.2s linear;

        .tree-item-level0 {
          position: sticky;
          top: 0;
          left: 0;
          width: 100%;
          height: 50px;

          display: flex;

          align-items: center;
          cursor: pointer;
          background-color: rgba(23, 44, 51, 1);

          .btn {
            margin-left: auto;
            width: 15%;
          }

          &:hover {
            background-color: rgba(23, 114, 153, 1);
          }

          .img {
            width: 20px;

            img {
              margin-top: 4px;
              transform-origin: center center;
              transition: all 0.2s linear;

              &.rotate {
                transform: rotate(90deg);
              }
            }
          }
        }

        // 500
        .tree-item-leave1 {
          width: 100%;
          height: 0;
          // 溢出
          overflow-y: auto;
          scrollbar-width: none;
          cursor: pointer;
          -ms-overflow-style: none;

          &::-webkit-scrollbar {
            display: none;
            /* Chrome Safari */
          }

          transition: all 0.2s linear;

          .children-item {
            width: 100%;
            height: 50px;
            display: flex;
            padding: 10px;
            box-sizing: border-box;
            background-color: rgba(124, 124, 124, 0.46);
            margin-top: 5px;

            &:hover {
              background-color: rgba(23, 114, 153, 1);
            }

            .alertContent {
              width: 50%;
              height: 30px;
              text-align: left;
              margin-left: 5%;
              line-height: 30px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .alertTime {
              width: 20%;
              height: 30px;
              text-align: right;
              line-height: 30px;
              text-align: center;
            }

            .btn {
              margin-left: 4%;
              width: 10%;
              margin-right: 1%;
            }

            .WARN {
              width: 15%;
              height: 30px;
              text-align: center;
              line-height: 30px;
              background-color: rgba(219, 172, 43, 0.24);
              border: 1px solid rgba(255, 207, 38, 1);
              border-radius: 5px;
              color: rgba(255, 207, 38, 1);
            }

            .INFO {
              width: 15%;
              height: 30px;
              text-align: center;
              line-height: 30px;
              background-color: rgba(38, 190, 255, 0.4);
              border: 1px solid rgba(38, 190, 255, 1);
              border-radius: 5px;
              color: rgba(38, 190, 255, 1);
            }

            .ERROR {
              width: 15%;
              height: 30px;
              text-align: center;
              line-height: 30px;
              background-color: rgba(92, 24, 20, 0.68);
              border: 1px solid rgba(224, 73, 40, 1);
              border-radius: 5px;
              color: rgba(224, 73, 40, 1);
            }
          }
        }
      }
    }
  }
}
</style>
